<template>
  <div 
    v-show="visible"
    class="customer-service-chat fixed bottom-24 right-4 z-50 w-96 max-w-[95vw] shadow-xl rounded-lg overflow-hidden transition-all duration-300"
    :class="{ 'opacity-100 translate-y-0': visible, 'opacity-0 translate-y-10': !visible }"
  >
    <!-- 聊天窗口头部 -->
    <div class="chat-header bg-gradient-to-r from-red-600 to-red-500 text-white p-3 flex justify-between items-center">
      <div class="flex items-center">
        <div class="avatar bg-white p-1 rounded-full mr-3">
          <img src="https://via.placeholder.com/32?text=CS" alt="客服头像" class="w-7 h-7 rounded-full">
        </div>
        <div>
          <h3 class="font-medium">{{ currentAgent.name }}</h3>
          <div class="text-xs flex items-center">
            <span class="inline-block w-2 h-2 rounded-full bg-green-400 mr-1"></span>
            <span>{{ currentAgent.status }}</span>
          </div>
        </div>
      </div>
      <div class="flex space-x-2">
        <el-tooltip content="静音模式" placement="top">
          <button @click="toggleMute" class="text-white opacity-80 hover:opacity-100 transition-opacity p-1">
            <el-icon :size="18"><Mute /></el-icon>
          </button>
        </el-tooltip>
        <el-tooltip content="最小化" placement="top">
          <button @click="minimize" class="text-white opacity-80 hover:opacity-100 transition-opacity p-1">
            <el-icon :size="18"><Minus /></el-icon>
          </button>
        </el-tooltip>
        <el-tooltip content="关闭" placement="top">
          <button @click="close" class="text-white opacity-80 hover:opacity-100 transition-opacity p-1">
            <el-icon :size="18"><Close /></el-icon>
          </button>
        </el-tooltip>
      </div>
    </div>
    
    <!-- 聊天窗口主体 -->
    <div class="chat-body bg-white h-96 flex flex-col">
      <!-- 聊天消息区 -->
      <div 
        ref="messagesContainer"
        class="messages flex-1 overflow-y-auto p-4 space-y-3"
      >
        <div v-for="(message, index) in messages" :key="index" class="message-wrapper">
          <!-- 系统消息 -->
          <div v-if="message.type === 'system'" class="system-message text-center">
            <span class="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded">{{ message.content }}</span>
          </div>
          
          <!-- 客服消息 -->
          <div 
            v-else-if="message.sender === 'agent'" 
            class="agent-message flex items-start"
          >
            <div class="avatar flex-shrink-0 bg-gray-100 p-1 rounded-full mr-2">
              <img :src="message.avatar || 'https://via.placeholder.com/28?text=CS'" alt="客服头像" class="w-6 h-6 rounded-full">
            </div>
            <div class="message-content max-w-[80%]">
              <div class="bg-gray-100 p-3 rounded-lg rounded-tl-none text-gray-700">
                <div v-if="message.isTyping" class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <div v-else v-html="formatMessage(message.content)"></div>
              </div>
              <div class="text-xs text-gray-400 mt-1">{{ formatTime(message.time) }}</div>
            </div>
          </div>
          
          <!-- 用户消息 -->
          <div 
            v-else-if="message.sender === 'user'" 
            class="user-message flex items-start justify-end"
          >
            <div class="message-content max-w-[80%]">
              <div class="bg-red-500 p-3 rounded-lg rounded-tr-none text-white">
                <div v-if="message.isTyping" class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <div v-else>{{ message.content }}</div>
              </div>
              <div class="text-xs text-gray-400 mt-1 text-right">{{ formatTime(message.time) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 快捷回复区 -->
      <div class="quick-replies bg-gray-50 p-2 border-t border-gray-100 overflow-x-auto whitespace-nowrap">
        <el-button 
          v-for="(reply, idx) in quickReplies" 
          :key="idx" 
          size="small" 
          plain 
          class="mr-2"
          @click="sendQuickReply(reply)"
        >
          {{ reply }}
        </el-button>
      </div>
      
      <!-- 聊天输入区 -->
      <div class="input-area p-3 border-t border-gray-200 flex flex-col">
        <div class="toolbar flex space-x-2 mb-2">
          <el-tooltip content="表情" placement="top">
            <el-popover placement="top" :width="300" trigger="click">
              <template #reference>
                <button class="text-gray-500 hover:text-red-500 transition-colors">
                  <el-icon :size="20"><ChatDotRound /></el-icon>
                </button>
              </template>
              <div class="emoji-picker grid grid-cols-6 gap-2 p-2">
                <button 
                  v-for="emoji in emojis" 
                  :key="emoji" 
                  @click="insertEmoji(emoji)"
                  class="text-xl hover:bg-gray-100 p-1 rounded"
                >
                  {{ emoji }}
                </button>
              </div>
            </el-popover>
          </el-tooltip>
          <el-tooltip content="上传图片" placement="top">
            <button class="text-gray-500 hover:text-red-500 transition-colors">
              <el-icon :size="20"><Picture /></el-icon>
            </button>
          </el-tooltip>
          <el-tooltip content="发送文件" placement="top">
            <button class="text-gray-500 hover:text-red-500 transition-colors">
              <el-icon :size="20"><Folder /></el-icon>
            </button>
          </el-tooltip>
          <el-tooltip content="语音通话" placement="top">
            <button class="text-gray-500 hover:text-red-500 transition-colors">
              <el-icon :size="20"><Headset /></el-icon>
            </button>
          </el-tooltip>
        </div>
        <div class="flex">
          <el-input
            v-model="messageInput"
            type="textarea"
            :rows="2"
            placeholder="请输入您的问题..."
            resize="none"
            @keydown.enter.prevent="sendMessage"
          />
          <el-button 
            type="primary" 
            class="ml-2 h-auto" 
            @click="sendMessage"
            :icon="Position"
          />
        </div>
      </div>
    </div>
    
    <!-- 版权信息 -->
    <div class="chat-footer bg-gray-50 p-2 border-t border-gray-200 text-xs text-center text-gray-500">
      阿蔓达医药商城客服系统 © {{ new Date().getFullYear() }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { 
  Mute, 
  Minus, 
  Close, 
  Picture, 
  Folder, 
  Headset, 
  Position, 
  ChatDotRound
} from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'minimize'])

interface Message {
  type?: 'normal' | 'system'
  sender: 'user' | 'agent'
  content: string
  time: Date
  avatar?: string
  isTyping?: boolean
}

// 客服信息接口
interface AgentInfo {
  id: string
  name: string
  avatar: string
  status: string
}

// 客服列表
const agents: AgentInfo[] = [
  { id: 'agent1', name: '客服小优', avatar: 'https://via.placeholder.com/32?text=小优', status: '在线' },
  { id: 'agent2', name: '客服小汇', avatar: 'https://via.placeholder.com/32?text=小汇', status: '在线' }
]

// 当前客服
const currentAgent = ref(agents[0])

// 聊天消息列表
const messages = ref<Message[]>([
  {
    type: 'system',
    sender: 'agent',
    content: '客服已接入，开始会话',
    time: new Date(Date.now() - 20 * 60000) // 20分钟前
  },
  {
    sender: 'agent',
    content: `您好，我是${agents[0].name}，很高兴为您服务。请问有什么可以帮助您的呢？`,
    time: new Date(Date.now() - 19 * 60000), // 19分钟前
    avatar: agents[0].avatar
  },
  {
    sender: 'user',
    content: '您好，我想咨询一下我的订单状态',
    time: new Date(Date.now() - 18 * 60000) // 18分钟前
  },
  {
    sender: 'agent',
    content: '好的，请问您的订单号是多少呢？我来帮您查询。',
    time: new Date(Date.now() - 17 * 60000), // 17分钟前
    avatar: agents[0].avatar
  },
  {
    sender: 'user',
    content: '2024071612345678',
    time: new Date(Date.now() - 16 * 60000) // 16分钟前
  },
  {
    sender: 'agent',
    content: '感谢您提供订单号。您的订单已经发货，物流单号是 SF1234567890，预计明天送达。<br>您可以<a href="#" class="text-blue-500">点击这里</a>查看物流详情。',
    time: new Date(Date.now() - 15 * 60000), // 15分钟前
    avatar: agents[0].avatar
  }
])

// 常用表情
const emojis = ['😊', '👍', '🙏', '❤️', '😂', '🎉', '👋', '🤔', '😭', '🥰', '😘', '😍', '🤗', '😅', '😁', '👏', '🎁', '🌹', '💯', '🔥', '✨', '⭐', '💫', '💎', '🌈', '☀️', '🌙', '⚡', '❄️', '☃️']

// 快捷回复
const quickReplies = [
  '如何查询订单?',
  '如何申请退款?',
  '商品什么时候发货?',
  '如何修改收货地址?',
  '优惠券使用说明'
]

// 输入的消息
const messageInput = ref('')
// 聊天消息容器
const messagesContainer = ref<HTMLElement | null>(null)
// 静音状态
const muted = ref(false)

// 发送消息
function sendMessage() {
  if (!messageInput.value.trim()) return
  
  // 添加用户消息
  messages.value.push({
    sender: 'user',
    content: messageInput.value,
    time: new Date()
  })
  
  // 清空输入
  messageInput.value = ''
  
  // 滚动到底部
  scrollToBottom()
  
  // 模拟客服正在输入
  messages.value.push({
    sender: 'agent',
    content: '',
    time: new Date(),
    avatar: currentAgent.value.avatar,
    isTyping: true
  })
  
  // 模拟客服回复
  setTimeout(() => {
    // 移除正在输入消息
    messages.value.pop()
    
    // 随机回复内容
    const responses = [
      '好的，我会帮您查询这个问题。',
      '您好，请稍等，我正在为您处理。',
      '感谢您的咨询，我已经了解您的问题了。',
      '您的问题我已经记录下来，稍后会给您回复。',
      '关于这个问题，我建议您可以尝试以下解决方案...'
    ]
    const randomResponse = responses[Math.floor(Math.random() * responses.length)]
    
    // 添加客服回复
    messages.value.push({
      sender: 'agent',
      content: randomResponse,
      time: new Date(),
      avatar: currentAgent.value.avatar
    })
    
    // 滚动到底部
    scrollToBottom()
  }, 1500)
}

// 发送快捷回复
function sendQuickReply(reply: string) {
  messageInput.value = reply
  sendMessage()
}

// 插入表情
function insertEmoji(emoji: string) {
  messageInput.value += emoji
}

// 滚动到聊天底部
function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 格式化消息时间
function formatTime(date: Date) {
  const now = new Date()
  const isSameDay = now.getDate() === date.getDate() && 
                    now.getMonth() === date.getMonth() && 
                    now.getFullYear() === date.getFullYear()
  
  if (isSameDay) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
  }
}

// 格式化消息内容（支持简单的HTML）
function formatMessage(content: string) {
  return content
}

// 切换静音
function toggleMute() {
  muted.value = !muted.value
}

// 最小化聊天窗口
function minimize() {
  emit('minimize')
}

// 关闭聊天窗口
function close() {
  emit('update:visible', false)
}

// 监听可见性变化
watch(() => props.visible, (newValue) => {
  if (newValue) {
    scrollToBottom()
  }
})

// 组件挂载完成
onMounted(() => {
  if (props.visible) {
    scrollToBottom()
  }
})
</script>

<style scoped>
.customer-service-chat {
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

/* 打字指示器动画 */
.typing-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 20px;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  margin: 0 2px;
  border-radius: 50%;
  background-color: currentColor;
  opacity: 0.4;
  display: inline-block;
  animation: typing 1.4s infinite both;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0% {
    transform: translateY(0);
  }
  28% {
    transform: translateY(-5px);
  }
  44% {
    transform: translateY(0);
  }
}

.emoji-picker::-webkit-scrollbar {
  width: 4px;
}

.emoji-picker::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 2px;
}

.messages::-webkit-scrollbar {
  width: 4px;
}

.messages::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 2px;
}

.quick-replies::-webkit-scrollbar {
  height: 4px;
}

.quick-replies::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 2px;
}
</style> 